const Question = require('../model/questions')
const User = require('../model/users')


class QuestionCtl {
  //检查话题是否存在
  async checkQuestionExist(ctx, next) {
    const question = await Question.findById(ctx.params.id).select("+questioner")
    if(!question) {
      ctx.throw(404, "问题不存在")
    }
    ctx.state.question = question
    await next()
  }
  //检查问题拥有着

  async checkQuestioner (ctx, next) {
    const { question } = ctx.state
    if(question.questioner.toString() !== ctx.state.user._id) {
      ctx.throw(403,'没有权限')
    }
    await next()
  }




  async find(ctx) {
    const { per_page = 3, page = 1 } = ctx.query
    const perpage = Math.max(per_page * 1, 1)
    const pages = Math.max(page * 1, 1) - 1
    const q = new RegExp(ctx.query.q)
    ctx.body = await Question.find({ $or: [{ title: q }, { description: q }]}).limit(perpage).skip(pages * perpage)
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectField = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const question = await Question.findById(ctx.params.id).select(selectField).populate('questioner topic')
    ctx.body = question
  }
  async create(ctx) {
    ctx.verifyParams({
      title: { type: 'string', required: true },
      description: { type: 'string', required: false },
    })
    const question = await new Question({...ctx.request.body, questioner: ctx.state.user._id}).save()
    ctx.body = question
  }

  async update(ctx) {
    ctx.verifyParams({
      title: { type: 'string', required: false },
      description: { type: 'string', required: false },
      topic: { type: 'string', required: false }
    })
     const question = await Question.findByIdAndUpdate(ctx.params.id, ctx.request.body)
     ctx.body = question
       
     
  }
  async del(ctx) {
    await Question.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }

  async listQuestionFollower(ctx) {
    const user = await User.find({followingTopic: ctx.params.id})
    ctx.body = user
  }
}
module.exports = new QuestionCtl()